package 场景.瞬间高并发请求.jdk;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 假如一个机器只能同时处理100个任务 同时模拟1000个任务并发请求
 * BlockingQueue 实现
 *
 * @author Administrator
 */
public class BlockingQueueDemo {
    /**
     * 模拟线程数
     */
    static final int MAX_THREAD = 1000;

    static final int MAX_RUN = 100;

    static CountDownLatch latch = new CountDownLatch(MAX_THREAD);

    static BlockingQueue<Integer> bq = new LinkedBlockingQueue<>(MAX_RUN);

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(MAX_THREAD);

        for (int i = 0; i < MAX_THREAD; i++) {
            final int id = i;
            Runnable run = () -> doWork(id);//都是调用doWork方法
            executor.submit(run);
            latch.countDown();
        }

        executor.shutdown();
        while (true) {
            if (executor.isTerminated()) {
                break;
            }
        }
    }

    public static void doWork(int id) {
        try {
            latch.await();//等线程都就绪后才开始执行
            if (!bq.offer(id, 3, TimeUnit.SECONDS)) {//offer 最多等待3秒不然失败
                System.out.println("【执行任务失败】:" + id);
            }
            Thread.sleep(300);// 模拟处理时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务已经处理完毕。。" + id);
        bq.remove(id);
    }

}
